#include "common.h"
#include "mmap_file.h"
#include "mmap_file_op.h"
#include "index_handle.h"
#include <sstream>

using namespace std;
using namespace zsyuung_fs;

const static largefile::MMapOption mmap_option = 
{
    1024000,
    4096,
    4096
};

const static uint32_t main_blocksize = 1024 * 1024 * 64;
const static uint32_t bucket_size = 1000;

static int32_t block_id = 1;

static int debug1 = 1;

int main(int argc, char* argv[])
{
    string mainblock_path;
    string index_path;
    int32_t ret = largefile::TFS_SUCCESS;

    cout << "Input blockid:" << endl;
    cin >> block_id;

    if(block_id < 1)
    {
        cerr << "invalid blockid" << endl;
        exit(-1);
    }

    largefile::IndexHandle* index_handle = new largefile::IndexHandle(".", block_id);

    if(debug1)
    {
        printf("init index...\n");
    }

    ret = index_handle->create(block_id, bucket_size, mmap_option);

    if(ret != largefile::TFS_SUCCESS)
    {
        fprintf(stderr, "create index failed, desc:%s\n", strerror(errno));
        delete index_handle;
        exit(-3);
    }

    stringstream tmp_stream;
    tmp_stream << "." << largefile::MAINBLOCK_DIR_PREFIX << block_id;
    tmp_stream >> mainblock_path;
    
    largefile::FileOperation* mainblock = new largefile::FileOperation(mainblock_path, O_CREAT | O_RDWR | O_LARGEFILE);

    ret = mainblock->ftruncate_file(main_blocksize);

    if(ret != 0)
    {
        fprintf(stderr, "create main block failed, desc:%s\n", strerror(errno));
        delete mainblock;
        index_handle->remove(block_id);
        exit(-2);
    }
    
    mainblock->close_file();
    index_handle->flush();

    delete mainblock;
    delete index_handle;
    return 0;
}
